import React, { useEffect, useState, useCallback } from "react";
import { Input, Form, Button, message, Select } from "antd";
import { getCurrentUser } from "../../api/oss/user";
import { roleAdd } from "../../api/oss/role";

const FormItem = Form.Item;
const { Option } = Select;

const AddNewRole = (props) => {
  const { modelData, callbackParent } = props;
  const [userId, setUserId] = useState(null);
  const [form] = Form.useForm();
  const getCurrUser = async () => {
    let res = await getCurrentUser();
    if (res.flag) {
      setUserId(res.data.id);
    }
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields().then(() => {
      let params = form.getFieldsValue();
      params.id = !props.modelData ? null : props.modelData.id;
      onSubmit(params);
    }).catch((e)=>{
      message.error("请检查表单信息是否符合要求")
    })
  };

  const onSubmit = async (data) => {
    let res = await roleAdd(data);
    if (res.flag) {
      message.success("请求成功");
      callbackParent();
    }
  };

  useEffect(() => {
    getCurrUser();
  }, []);

  const { getFieldError, isFieldValidating } = form;

  const formItemLayout = {
    layout: "horizontal",
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
    labelAlign: "left",
  };

  return (
    <Form {...formItemLayout} form={form}>
      <FormItem
        label="名称："
        name="name"
   
        rules={[{ required: true, message: "请填写用户名" }]}
        initialValue={modelData ? modelData.name : null}
      >
        <Input placeholder="名称" />
      </FormItem>
      <FormItem
        label="简写"
        name="shortName"
        rules={[{ required: true, message: "请填写简写" }]}
        initialValue={modelData ? modelData.shortName : null}
      >
        <Input placeholder="简写" />
      </FormItem>
      <FormItem
        label="是否脱敏："
        name="displayType"
        rules={[{ required: true, message: "请选择是否脱敏" }]}
        initialValue={modelData ? modelData.displayType : null}
      >
        <Select style={{ width: 180 }} placeholder="是否脱敏">
          <Option value="FULL">展示完整数据</Option>
          <Option value="MASKING">展示脱敏后的数据</Option>
        </Select>
      </FormItem>
      <FormItem
        label="描述"
        name="description"
        rules={[{ required: true, message: "请填写描述" }]}
        initialValue={modelData ? modelData.description : null}
      >
        <Input type="textarea" placeholder="描述" />
      </FormItem>

      <FormItem wrapperCol={{ span: 12, offset: 10 }}>
        <Button type="primary" onClick={handleSubmit}>
          确定
        </Button>
      </FormItem>
    </Form>
  );
};

export default AddNewRole;
